﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Xml;
using System.Windows.Forms;
using MES.DataGateway.SyncEntity;
using MES.DataGateway.Common;
using MES.DataGateway.OracleDAL;
using MES.DataGateway.SyncCommon;
using MES.DataGateway.SyncInterface;
using MES.DataGateway.StandardEntity;
using System.IO;
using System.Configuration;

namespace MES.DataGateway.StandardDataSync
{
    /// <summary>
    /// 超越单
    /// </summary>
    public class Surpass
    {
        private string m_DataFilePath = "";
        private string m_AccessoriesPath = "";//add:Wangjh 20171121 
        private string m_xmlName = "";//20180103
        private string m_strProductName = "";
        private StandardDAL m_dal;
        public string DataFilePath
        {
            get { return m_DataFilePath; }
            set { m_DataFilePath = value; }
        }

        public void Execute()
        {
            m_dal = new StandardDAL();
            ReadXML(m_DataFilePath);
        }
        /// <summary>
        /// 读取xml数据
        /// </summary>
        /// <param name="strPath"></param>
        private void ReadXML(string strPath)
        {
            string strSurpassID = string.Empty, strSurpassVersion = string.Empty, strSurpassName = string.Empty;
            string strProductName = string.Empty, strProductDesc = string.Empty;
            string strWorkflowNO = string.Empty, strFileNO = string.Empty;
            string strFactory = string.Empty, strContainer = string.Empty, strEffective = string.Empty;
            XmlDocument myxml = new XmlDocument();
            myxml.Load(strPath);
            m_xmlName = new FileInfo(strPath).Name;
            //获取超越单信息
            XmlNode stu = myxml.SelectSingleNode("/Root/surpass/item_id");//超越单ID
            strSurpassID = stu.InnerText.Trim();
            stu = myxml.SelectSingleNode("/Root/surpass/item_revision_id");//超越单版本
            strSurpassVersion = stu.InnerText.Trim();
            stu = myxml.SelectSingleNode("/Root/surpass/object_name");//超越单名称
            strSurpassName = stu.InnerText.Trim();
            stu = myxml.SelectSingleNode("/Root/surpass/ly2processfile_partno");//零件图号
            strProductName = stu.InnerText.Trim();
            m_strProductName = strProductName;
            stu = myxml.SelectSingleNode("/Root/surpass/ly2processfile_partname");//零件名称
            strProductDesc = stu.InnerText.Trim();
            stu = myxml.SelectSingleNode("/Root/surpass/ly2processfile_no");//工艺规程编号
            strWorkflowNO = stu.InnerText.Trim();
            stu = myxml.SelectSingleNode("/Root/surpass/ly2file_no");//文件编号
            strFileNO = stu.InnerText.Trim();
            stu = myxml.SelectSingleNode("/Root/surpass/ly2plant");//车间
            strFactory = stu.InnerText.Trim();
            stu = myxml.SelectSingleNode("/Root/surpass/ly2batch");//批次
            strContainer = stu.InnerText.Trim();
            stu = myxml.SelectSingleNode("/Root/surpass/ly2effective");//有效期
            strEffective = stu.InnerText.Trim();
            DataTable detailDT = new DataTable();
            detailDT.Columns.Add("SurpassType");
            detailDT.Columns.Add("SurpassOp");
            detailDT.Columns.Add("Remark");
            stu = myxml.SelectSingleNode("/Root/surpass/rowdatas");//内容列表
            foreach (XmlNode node in stu.ChildNodes)
            {
                if (node.Name != "rowdata")
                    continue;
                if (node.ChildNodes.Count == 0)
                { continue; }
                DataRow dr = detailDT.NewRow();
                dr["SurpassType"] = node.SelectSingleNode("type").InnerText.Trim();
                dr["SurpassOp"] = node.SelectSingleNode("meops").InnerText.Trim();
                dr["Remark"] = node.SelectSingleNode("remark").InnerText.Trim();
                detailDT.Rows.Add(dr);
            }
            //存放附件add:Wangjh 20171120
            DataTable AccessoriesDT = new DataTable();
            AccessoriesDT.Columns.Add("SurpassID");
            AccessoriesDT.Columns.Add("AccessoriesPath");
            AccessoriesDT.Columns.Add("SurpassNo");
            AccessoriesDT.Columns.Add("AccessoriesFolder");//存放附件的文件夹
            stu = myxml.SelectSingleNode("/Root/surpass/Doc");//附件列表

            string strTmp = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().Trim() + DateTime.Now.Day.ToString() +
                                DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
            foreach (XmlNode node in stu.ChildNodes)
            {
                if (node.Name != "FileName")
                    continue;
                if (node.ChildNodes.Count == 0)
                    continue;
                DataRow dr = AccessoriesDT.NewRow();
                dr["SurpassID"] = strSurpassID;
                dr["AccessoriesPath"] = strFileNO + strTmp + "\\" + node.InnerText.Trim();
                dr["AccessoriesFolder"] = strFileNO + strTmp;
                dr["SurpassNo"] = strFileNO;
                AccessoriesDT.Rows.Add(dr);
            }
            strTmp = "";
            //
            SortedList<string, object> dict = new SortedList<string, object>();
            dict.Add("SurpassBillInfoID", strSurpassID);
            dict.Add("SurpassBillInfoName", strSurpassName);
            dict.Add("SurpassBillInfoRevision", strSurpassVersion);
            dict.Add("ProductName", strProductName);
            dict.Add("ProductDes", strProductDesc);
            dict.Add("FileNO", strFileNO);
            dict.Add("ProcessNO", strWorkflowNO);
            dict.Add("FactoryName", strFactory);
            dict.Add("ContainerName", strContainer);
            dict.Add("Effective", strEffective);

            SaveSurpass(dict, detailDT);
            //存入附件
            SaveAccessories(AccessoriesDT);
        }
        /// <summary>
        /// 保存超越单
        /// </summary>
        private void SaveSurpass(SortedList<string, object> dict, DataTable detailDT)
        {
            if (!m_dal.InsertSurpassInfo(dict))
            {
                return;
            }
            SortedList<string, object> DetailList = new SortedList<string, object>();
            foreach (DataRow dr in detailDT.Rows)
            {
                DetailList.Clear();
                DetailList.Add("SurpassBillInfoID", dict["SurpassBillInfoID"]);
                DetailList.Add("SurpassBillDetailID", Guid.NewGuid().ToString());
                DetailList.Add("SurpassType", dr["SurpassType"]);
                DetailList.Add("SurpassOP", dr["SurpassOp"]);
                DetailList.Add("Remark", dr["Remark"]);
                if (!m_dal.InsertSurpassDetail(DetailList))
                {
                    return;
                }
                if (SaveSurpassMapping(DetailList["SurpassBillDetailID"].ToString(), dict["ContainerName"].ToString(),
                      dict["ProductName"].ToString(), dict["ProcessNO"].ToString(), DetailList["SurpassOP"].ToString()) == false)
                    return;
            }


        }
        /// <summary>
        /// 超越单映射系统批次ID
        /// </summary>
        /// <param name="SurpassBillDetailID"></param>
        /// <param name="strContainers"></param>
        /// <param name="strProduct"></param>
        /// <param name="ProcessNO"></param>
        /// <param name="strSpecNos"></param>
        private Boolean SaveSurpassMapping(string SurpassBillDetailID, string strContainers, string strProduct, string ProcessNO, string strSpecNos)
        {
            string[] strContainerlist = strContainers.Split('#');
            string[] strSpeclist = strSpecNos.Split(';');

            string containerNames = "";
            foreach (string container in strContainerlist)
            {
                containerNames = string.Format("{0}'{1}/{2}',", containerNames, strProduct, container);
            }
            if (string.IsNullOrWhiteSpace(containerNames))
            {
                containerNames = string.Format("'{0}/{1}'", strProduct, containerNames);
            }
            else
            {
                containerNames = containerNames.Remove(containerNames.Length - 1);
            }
            DataTable containerDT = m_dal.GetContainers(containerNames);
            SortedList<string, object> mappingList = new SortedList<string, object>();
            if (containerDT.Rows.Count == 0) //add:Wangjh
            {
                Log.WriteOrcale("PDMTOMES_Surpass" + "@^" + "系统中无对应批次:" + containerNames + "@^" + m_xmlName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strProductName);//add:Wangjh 写入数据库
                return false;
            }
            foreach (DataRow dr in containerDT.Rows)
            {
                foreach (string strSpec in strSpeclist)
                {
                    mappingList.Clear();
                    mappingList.Add("SurpassBillDetailID", SurpassBillDetailID);
                    mappingList.Add("ContainerID", dr["ContainerID"]);
                    mappingList.Add("ProcessNO", ProcessNO);
                    mappingList.Add("SpecNO", strSpec);
                    m_dal.InsertSurpassMapping(mappingList);
                    Log.WriteOrcale("PDMTOMES_Surpass" + "@^" + "批次:" + dr["Containername"] + "超越单创建成功" + "@^" + m_xmlName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strProductName);//add:Wangjh 写入数据库
                }
            }
            return true;
        }
        /// <summary>
        /// 保存附件
        /// add:Wangjh 20171121
        /// </summary>
        /// <param name="dt"></param>
        private void SaveAccessories(DataTable dt)
        {
            //移动到系统储存超越单位置
            m_AccessoriesPath = ConfigurationManager.AppSettings["AccessoriesPath"];

            DataTable tempDt = dt.DefaultView.ToTable(true, "SurpassID", "SurpassNo", "AccessoriesFolder");

            foreach (DataRow dr in tempDt.Rows)
            {
                if (!Directory.Exists(m_AccessoriesPath + "\\" + dr["SurpassNo"].ToString()))
                {
                    Log.WriteOrcale("PDMTOMES_Surpass" + "@^" + "无路径：" + m_AccessoriesPath + "\\" + dr["SurpassNo"].ToString() + "@^" + m_xmlName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strProductName);//add:Wangjh 写入数据库
                    continue;
                }
                DirectoryInfo SurpassAcceDr = new DirectoryInfo(m_AccessoriesPath + "\\" + dr["SurpassNo"].ToString());//原先存放附件的路径

                foreach (FileInfo fi in SurpassAcceDr.GetFiles())
                {
                    string tempPath = ConfigurationManager.AppSettings["CamstarPathTemp"] + dr["AccessoriesFolder"].ToString();//存放附件的文件夹路径
                    if (!Directory.Exists(tempPath))
                    {
                        Directory.CreateDirectory(tempPath);
                    }
                    fi.MoveTo(tempPath + "\\" + fi.Name);
                }
                SurpassAcceDr.Delete();
            }
            //插入超越单储存位置信息
            foreach (DataRow dr in dt.Rows)
            {
                string surpassBillInfoID = dr["SurpassID"].ToString();
                string accessoriesPath = dr["AccessoriesPath"].ToString();
                if (!m_dal.InsertSurpassAccessories(surpassBillInfoID, accessoriesPath))
                {
                    return;
                }
            }
            return;
        }
    }
}
